var express=require('express');
var app=express();

app.use(require('body-parser')());

var mongoose=require('mongoose');
var options={
    keepAlive:1,
    useMongoClient: true
};
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/backmanagedb');
var db = mongoose.connection;
//var db=mongoose.createConnection('mongodb://localhost:27017/gomall');
db.on('error', function(e) {console.log(e)});
db.once('open',function (){
    console.log("数据库链接成功"); //gang cai hai nneg dakai

});

var cookieParser = require('cookie-parser');
var session=require('express-session');
app.use(cookieParser('sessiontest'));
app.use(session({
    secret: 'sessiontest',//与cookieParser中的一致
    cookie: { maxAge: 1000*60*10 },
    resave: true,
    saveUninitialized:true,
    rolling:true
}));

var handlebars = require('express-handlebars')
    .create({
        defaultLayout: 'main',
        extname:".hbs",
        helpers: {
            static: function(name) {
                return require('./lib/static.js').map(name);
            },
            section : function(name, options) {
                if(!this._sections) this._sections = {};
                this._sections[name] = options.fn(this);
                return null;
            }
        }
    });
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.use('/',express.static(__dirname + '/public'));
app.use('/admin',express.static(__dirname + '/public'));
app.use('/admin/main',express.static(__dirname + '/public'));


var route=require('./routes/route.js');
var adminLogin=require('./routes/adminLogin.js');
app.use('/admin',adminLogin);

app.use('/admin/main',loginConfirm);
app.use('/admin/main',route);
function loginConfirm(req,res,next){
    if(req.session.user){
       next();
    }else{
    console.log("没登录就想进去!-!")
        res.redirect('/admin/login');
    }
}



app.set('port',process.env.PORT || 1123);
app.listen(app.get('port'),function () {
    console.log('Express Started on http://localhost:'+app.get('port')+'; press Ctrl + C to terminate');
});